package fr.inserm.umr915.libjson;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.w3c.dom.Document;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public abstract class StringNode extends Node
	{
	static final String TAG="string";
	private String value;
	public StringNode(String value)
		{
		this.value=value;
		}
	
	public static void escape(PrintWriter out,String s)
		{
		out.print("\"");
		for(int i=0;i< s.length();++i)
			{
			switch(s.charAt(i))
				{
				case '\"':  out.print("\\\""); break;
				case '\'':  out.print("\\\'"); break;
				case '\\':  out.print("\\\\"); break;
				case '\n':  out.print("\\n"); break;
				case '\r':  out.print("\\r"); break;
				case '\t':  out.print("\\t"); break;
				default: out.print(s.charAt(i)); break;
				}
			}	
		out.print("\"");
		}
	
	@Override
	public void print(PrintWriter out)
		{
		escape(out,getValue());
		}
	
	public String getValue()
		{
		return this.value;
		}
	
	@Override
	public Node clone(NodeFactory owner)
		{
		return owner.createStringNode(getValue());
		}
	
	@Override
	public NodeType getNodeType()
		{
		return NodeType.STRING;
		}
	
	@Override
	public void write(DataOutputStream out) throws IOException
		{
		out.writeByte((byte)getNodeType().ordinal());
		out.writeUTF(getValue());
		}
	
	public org.w3c.dom.Element asDom(Document owner)
		{
		org.w3c.dom.Element root= owner.createElement(TAG);
		root.appendChild(owner.createTextNode(getValue()));
		return root;
		}
	
	@Override
	public void write(XMLStreamWriter out) throws XMLStreamException
		{
		out.writeStartElement(TAG);
		out.writeCharacters(getValue());
		out.writeEndElement();
		}
	
	@Override
	protected void saxHandler(ContentHandler handler) throws SAXException,
			IOException
		{
		handler.startElement("", "", TAG, new AttributesImpl());
		char ch[]=String.valueOf(getValue()).toCharArray();
		handler.characters(ch, 0, ch.length);
		handler.endElement("", "", TAG);
		}
	
	@Override
	public String toString()
		{
		return getValue();
		}
	}
